package com.loooooo.pm2024.modules.pm.service;


import com.loooooo.pm2024.exception.MyBaseException;
import com.loooooo.pm2024.modules.pm.mapper.AttachmentMapper;
import com.loooooo.pm2024.modules.pm.model.Attachment;
import com.loooooo.pm2024.modules.pm.selector.AttachmentSelector;
import com.loooooo.pm2024.security.SecurityUtils;
import com.loooooo.pm2024.service.IdService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class AttachmentService {

    @Autowired
    AttachmentMapper attachmentMapper;
    @Autowired
    IdService idService;
    @Autowired
    TransactionTemplate transactionTemplate;

    public Attachment get(Long id) {
        return get(id, null);
    }

    public Attachment get(Long id, AttachmentSelector selector) {
        Attachment attachment = attachmentMapper.get(id);
        if (attachment != null && selector != null) {
//            if (Objects.equals(1, selector.getWithLogList())) {
//                AttachmentLogSelector logSelector = new AttachmentLogSelector();
//                logSelector.getTarget().setAttachmentId(attachment.getId());
//                List<AttachmentLog> logList = attachmentLogService.list(logSelector);
//                attachment.setLogList(logList);
//            }
        }
        return attachment;
    }


    public List<Attachment> list(AttachmentSelector selector) {
        List<Attachment> list = attachmentMapper.select(selector);
        if (list.size() > 0) {
//            if (Objects.equals(1, selector.getWithLogList())) {
//                AttachmentLogSelector logSelector = new AttachmentLogSelector();
//                logSelector.setAttachmentIdList(list.stream().map(x -> x.getId()).distinct().collect(Collectors.toList()));
//                List<AttachmentLog> logList = attachmentLogService.list(logSelector);
//                if (logList.size() > 0) {
//                    for (Attachment attachment : list) {
//                        attachment.setLogList(logList.stream().filter(x -> Objects.equals(attachment.getId(), x.getAttachmentId())).collect(Collectors.toList()));
//                    }
//                }
//            }
        }
        return list;
    }

    public int count(AttachmentSelector selector) {
        return attachmentMapper.count(selector);
    }

    public int update(Attachment issue, MultipartFile multipartFile) {
        long now = System.currentTimeMillis();
        issue.setUpdatedAt(now);
        Long userId = SecurityUtils.loginedUserId();
        issue.setUpdatedBy(userId);
        if (multipartFile != null && !multipartFile.isEmpty()) {
            issue.setFilename(multipartFile.getOriginalFilename());
            issue.setSize((int) multipartFile.getSize());
            issue.setContentType(multipartFile.getContentType());
        }

        int r = transactionTemplate.execute(new TransactionCallback<Integer>() {
            @Override
            public Integer doInTransaction(TransactionStatus status) {
                if (issue.getId() == null || issue.isNewEntity() || issue.getId() <= 0L) {
                    if (userId == null) {
                        MyBaseException.throwMe(10401, "未登录");
                    }
                    if (issue.getId() == null || issue.getId() <= 0L) {
                        issue.setId(idService.nextId());
                    }
                    if (issue.getOwnerId() == null) {
                        MyBaseException.throwMe(10401, "用户未指定");
                    }
                    if (issue.getIssueId() == null) {
                        MyBaseException.throwMe(10401, "Issue未指定");
                    }
                    issue.setCreatedAt(now);
                    issue.setCreatedBy(userId);
                    issue.setNew(false);
                    attachmentMapper.insert(issue);
                }
                if (multipartFile != null && !multipartFile.isEmpty()) {
                    File dir = new File("/image2/pm2024/attachment/", (issue.getId() + "").substring(0, 2) + "/" + (issue.getId() + "").substring(2) + "/" + issue.getFilename());
                    if (!dir.getParentFile().exists()) dir.getParentFile().mkdirs();
                    try {
                        multipartFile.transferTo(new File(dir.getAbsolutePath()));
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
                return attachmentMapper.update(issue);
            }
        });
        return r;


    }


}
